﻿using Microsoft.WindowsAzure.Storage.Blob;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace POC.Azure.Storage
{
    public class BlobStorageRepository : IBlobStorageRespository<MessageFormat>
    {
        AzureAccount _account;
   
        string _containerName = "session";
        private int maxMessages;
        string _blobName = "anonymoussession" + Guid.NewGuid().ToString("N");
        CloudBlobClient _client;
        ICloudBlob _blob;
        string mime = "application/octet-stream";
        public BlobStorageRepository(CloudBlobClient client, string containerName)
        {
            _client = client;
            _containerName = containerName;
        }
        public BlobStorageRepository(AzureAccount account, string containerName)
        {
            _account = account;
            _client=    _account.CloudAccount.CreateCloudBlobClient();
            _containerName = containerName;
        }      

        public void InitializeRepository()
        {
            if (_blob == null)
            {
                var root = _client.GetContainerReference(_containerName);
                root.CreateIfNotExists();
                _blob = root.GetBlockBlobReference(_blobName);
            }
        }
        public void WriteFromStream(Stream stream, string name)
        {
            _blobName = name;
            InitializeRepository();
            _blob.Properties.ContentType = mime;
            stream.Seek(0, SeekOrigin.Begin);
            _blob.UploadFromStream(stream);
        }

        public void ReadToStream(Stream stream, string name)
        {
            _blobName = name;
            InitializeRepository();
            _blob.Properties.ContentType = mime;
            _blob.DownloadToStream(stream);
            stream.Seek(0, SeekOrigin.Begin);
            Debug.WriteLine("Size = " + stream.Length);
        }

        public bool Delete(string uri)
        {
            bool deleted = false;
            try
            {
                var root = _client.GetContainerReference(_containerName);
                var blob = _client.GetBlobReferenceFromServer(new Uri(uri));
                blob.Delete();
            }
            catch (Exception csx)
            {
            }
            return deleted;
        }


        public IEnumerable<IListBlobItem> ListBlobs(string prefix)
        {
            var root = _client.GetContainerReference(_containerName);
            return root.ListBlobs(prefix);
        }
    }
}
